<template>
	<div>
		<zh-row :gutter="8">
			<zh-col :span="6">
				<zh-card>
					<zh-tree
						:height="662"
						ref="orgTreeRef"
						:showSearch="false"
						funcCode="org0032"
						:nodeLevel="1"
						:expand-on-click-node="false"
						:queryParam="queryTreeParam"
						node-key="orgId"
						:lazy="true"
						:pagging="true"
						:props="{ label: 'orgName' }"
						:resultFields="{ treeList: 'list' }"
						@node-click="onNodeClick"
					></zh-tree>
				</zh-card>
			</zh-col>
			<zh-col :span="12">
				<zh-form ref="userQueryForm" :model="queryUserParam">
					<zh-form-input
						:span="12"
						prop="searchValue"
						@input="onSearhValueInput"
						label=""
						placeholder="请选择搜索类型后输入搜索"
						v-model="queryUserParam.searchValue"
					>
						<template #prepend>
							<el-select v-model="queryUserParam.searchType" placeholder="选择类型" style="width: 100px" @change="onSearchTypeChange">
								<el-option label="账号" value="userName" />
								<el-option label="用户名" value="fullName" />
								<el-option label="证件号码" value="idcard" />
								<el-option label="手机号码" value="cellphone" />
							</el-select>
						</template>
					</zh-form-input>
					<zh-form-query :form-ref="userQueryForm" :table-ref="userListTable" :show-advanced="false"></zh-form-query>
				</zh-form>
				<zh-table
					ref="userListTable"
					:title="state.leftTitle"
					:rowConfig="{ keyField: 'userId' }"
					:height="610"
					funcCode="user0037"
					:columns="state.userColumn"
					:disabledList="state.myCheckList"
				>
					<template #header>
						<div class="card-header">
							<span>{{ state.leftTitle }}</span>
							<el-button v-if="props.mode === 'multiple'" type="primary" plain @click="addAll">添加当前数据</el-button>
						</div>
					</template>
					<template #operateUser="{ row }">
						<zh-button :key="row.disabled" :type="row.disabled ? 'info' : 'primary'" @click="add(row)" :disabled="row.disabled">{{
							row.disabled ? '已选择' : '添加'
						}}</zh-button>
					</template>
				</zh-table>
			</zh-col>
			<zh-col :span="6">
				<zh-table
					ref="userCheckTable"
					:rowConfig="{ keyField: 'userId' }"
					:height="665"
					:title="state.rightTitle"
					:data="state.myCheckList"
					:columns="state.checkOrgColumn"
					:layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump']"
				>
					<template #header>
						<div class="card-header">
							<span>{{ state.rightTitle }}</span>
							<el-button v-if="props.mode === 'multiple'" type="danger" plain @click="delAll">全部移除</el-button>
						</div>
					</template>
					<template #operate="{ row }">
						<zh-button type="danger" @click="del(row)">移除</zh-button>
					</template>
				</zh-table>
			</zh-col>
		</zh-row>
	</div>
</template>
<script lang="ts" setup name="orgUserSelect">
import { ElMessage } from 'element-plus';
// ------------------接收传入参数(组件)-------------------
const props = defineProps({
	modelValue: {
		type: [String, Array],
		default: undefined,
	},
	//模式：multiple 多选
	mode: {
		type: String,
		default() {
			return '';
		},
	},
	checkList: {
		type: Array,
		default: () => {
			return [];
		},
	},
	//组织类型
	orgTypeList: {
		type: Array,
		default: () => {
			return [];
		},
	},
	//用户类型
	userTypeList: {
		type: Array,
		default: () => {
			return ['10'];
		},
	},
	//最大可选人数
	max: {
		type: Number,
		default: 200,
	},
	//最小选择人数
	min: {
		type: Number,
		default: 0,
	},
});
// ------------------钩子函数----------------------------

// 初始化
onMounted(() => {
	nextTick(() => {
		userListTable.value.query();
		state.myCheckList = props.checkList.slice();
	});
});
watch(
	() => props.checkList,
	() => {
		state.myCheckList = props.checkList.slice();
	},
	{
		deep: true,
	}
);

// ------------------定义子组件--------------------------
const userQueryForm = ref<any>({});
const userListTable = ref<any>({});
const userCheckTable = ref<any>({});
// ------------------变量区------------------------------
const queryTreeParam = ref({ parentKey: '', orgTypes: props.orgTypeList });
const queryUserParam = ref({
	orgId: '',
	searchValue: '',
	userName: '',
	fullName: '',
	idcard: '',
	cellphone: '',
	searchType: 'fullName',
	orgTypes: props.orgTypeList,
	userTypeList: props.userTypeList,
});
const state = reactive({
	leftTitle: '待选择列表',
	funcCode: '',
	rightTitle: '已选择0条',
	myCheckList: [] as any,
	userColumn: [
		{
			field: 'operateUser',
			title: '操作',
			fixed: 'left',
			align: 'center',
			width: 100,
			slots: {
				// 使用插槽模板渲染
				default: 'operateUser',
			},
		},
		{ field: 'userId', title: '用户id', visible: false, fixed: 'left', align: 'center', width: 150 },
		{ field: 'fullName', title: '用户名', align: 'center', fixed: 'left', minWidth: 200 },
		{ field: 'userName', title: '账号', align: 'center', minWidth: 100 },
		{ field: 'orgName', title: '所属组织', align: 'center', minWidth: 200 },
	],
	checkOrgColumn: [
		{
			field: 'operate',
			title: '操作',
			fixed: 'left',
			align: 'center',
			width: 100,
			slots: {
				// 使用插槽模板渲染
				default: 'operate',
			},
		},
		{ field: 'userId', title: '用户id', visible: false, fixed: 'left', align: 'center', width: 150 },
		{ field: 'fullName', title: '用户名', align: 'center', fixed: 'left', minWidth: 200 },
		{ field: 'userName', title: '账号', align: 'center', minWidth: 100 },
	],
});
// ------------------方法区------------------------------
const onNodeClick = (row: any) => {
	queryUserParam.value.orgId = row.key;
	userListTable.value.query(queryUserParam.value);
};
const emit = defineEmits(['update:modelValue', 'change']);

const add = (row) => {
	let list = state.myCheckList;
	if (list && list.length > 0) {
		if (list.length > props.max) {
			ElMessage.warning('已达选择上限，选择用户不能大于' + props.max + '人');
			return;
		}
		if (props.mode === 'multiple') {
			let hasList = list.filter((item) => item.userId === row.userId);
			if (hasList && hasList.length > 0) {
				ElMessage.warning('该用户已选择');
				return;
			} else {
				list.push(row);
			}
		} else {
			ElMessage.warning('只可选择一条');
			return;
		}
	} else {
		list.push(row);
	}
	state.rightTitle = '已选择' + list.length + '条';
	state.myCheckList = list;
};
const del = (row) => {
	let list = state.myCheckList;
	if (list && list.length > 0) {
		let hasList = list.filter((item) => item.userId !== row.userId);
		state.rightTitle = '已选择' + hasList.length + '条';
		state.myCheckList = hasList;
	}
};
const addAll = () => {
	let addlist = userListTable.value.tableData;
	if (addlist && addlist.length > 0) {
		let list = state.myCheckList || [];
		addlist.forEach((item) => {
			if (!item.disabled) {
				let hasList = list.filter((checkItem) => checkItem.userId === item.userId);
				if (!hasList || hasList.length <= 0) {
					list.push(item);
				}
			}
		});
		if (list.length > props.max) {
			ElMessage.warning('已达选择上限，选择用户不能大于' + props.max + '人');
			return;
		}
		state.myCheckList = list;
	} else {
		ElMessage.warning('没有可添加的数据');
	}
};
const delAll = () => {
	state.myCheckList = [];
};
const success = () => {
	emit('change', state.myCheckList);
};
const onSearhValueInput = () => {
	onSearchTypeChange(queryUserParam.value.searchType);
};
const onSearchTypeChange = (val) => {
	//查询类型选择时处理
	if (val === 'userName') {
		queryUserParam.value.userName = queryUserParam.value.searchValue;
	} else if (val === 'fullName') {
		queryUserParam.value.fullName = queryUserParam.value.searchValue;
	} else if (val === 'cellphone') {
		queryUserParam.value.cellphone = queryUserParam.value.searchValue;
	} else if (val === 'idcard') {
		queryUserParam.value.idcard = queryUserParam.value.searchValue;
	}
	console.log(queryUserParam.value.searchValue);
	console.log(queryUserParam.value);
};

defineExpose({
	...toRefs(state),
	success,
});
</script>
<style lang="scss" scoped>
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.search-text-color {
	color: var(--el-color-primary);
}
</style>
